package com.fysports.web.controller.commons;

import com.google.common.collect.Maps;
import com.jfinal.aop.Clear;
import com.jfinal.core.ActionKey;
import com.jfinal.json.Json;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.upload.UploadFile;
import com.fysports.framework.render.MimeTypeRender;
import com.fysports.web.config.AppConst;
import com.fysports.web.controller.AbstractBaseController;
import com.fysports.web.controller.ControllerException;
import com.fysports.web.event.upload.UploadEvent;
import com.fysports.web.kit.commons.FileKit;
import com.fysports.web.kit.commons.StringKit;
import com.fysports.web.kit.umeditor.DownLoadFileParse;
import com.fysports.web.kit.umeditor.Uploader;
import com.fysports.web.kit.upload.DefaultUploadHelper;
import com.fysports.web.kit.upload.UploadHelper;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;


/**
 * 系统的上传目录格式 <br>
 * 使用方式:<br/>
 * 1.需要在sysconfig.propertis中配置过滤路径 <br/>
 * 2.在DownRouteHandler中添加路由正则
 * path:/标志/主键/文件名.后缀
 * Created by konbluesky
 * Date : 14-8-25 下午2:19
 * modifyDate:15-12-30 10:50
 * Project : JdmData_WebServer
 */
@Clear
public class UpAndDownController extends AbstractBaseController {
    private static Log logger=Log.getLog(UpAndDownController.class);
    /**
     * 上传目录
     * /up
     * @param //modulename -> moduleName
     */
    @ActionKey("up")
    public void index() {
        UploadFile uf = getFile();
        File f = uf.getFile();
        /*上传文件的保存目录标志符*/
        String upflag = getPara("modulename", UploadEvent.UploadModule.UNKNOW.toString());
        String bizuuid = getPara("bizuuid");
        if(StringKit.isBlank(bizuuid)){
            throw new ControllerException("业务UUID,不能为空");
        }
        UploadHelper uploadhelper=new DefaultUploadHelper(uf,upflag,bizuuid);
        try {
            uploadhelper.upload();
        }
        catch (Exception e) {
            logger.error(e.getLocalizedMessage(),e);
            throw new ControllerException(e);
        }
        renderJson(uploadhelper.getResult());
    }

    /**
     * 通过actionKey指定
     * /down 与 /up 平级
     */
    @ActionKey("down")
    public void down() {
        String params = getPara();
        DownLoadFileParse file = new DownLoadFileParse(params);
        String path = FileKit.getFileNameByUME(file);
        /**
         * ume上传后,文件保存在tmp目录,只有当业务逻辑成功执行
         * eventbus才会将tmp->real; 所以此处要对path做兼容处理;
         *
         * 1.real目录没有,查找tmp
         * 2.tmp目录没有return null
         */
        File f=new File(path);
        if(!f.exists()){
            path = PropKit.use(AppConst.CONFIG_SYSTEM).get(AppConst.UPLOAD_TMPPATH);
            path += file.getHttpUrl();
        }
        File f2=new File(path);
        if(f2.exists()){
            render(new MimeTypeRender(file.getSuffix(), path));
        }else{
            renderNull();
        }
    }
    @ActionKey("umeup")
    public void umeup(){
        try {
            getRequest().setCharacterEncoding("utf-8");
            getResponse().setCharacterEncoding("utf-8");
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error(e.getLocalizedMessage(), e);
        }

        Uploader up = new Uploader(getRequest());
        /*
        * 此处设置的路径，用LoadImageHandler 路由 以参数的方式转到loadimg()方法中。
        * */
        String modulename=getPara("modulename", UploadEvent.UploadModule.UNKNOW.toString());
        String bizuuid=getPara("bizuuid");
        up.setSavePath(modulename);
        up.setBizuuid(bizuuid);
        String[] fileType = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        try {
            up.upload();
        }
        catch (Exception e) {
            logger.error("umedtor 上传错误",e);
            throw new ControllerException(e);
        }

        Map<String, Object> vals = Maps.newHashMap();
        vals.put("name", up.getFileName());
        vals.put("originalName", up.getOriginalName());
        vals.put("size", up.getSize());
        vals.put("state", up.getState());
        vals.put("type", up.getType());
        vals.put("url", up.getUrl());

        String result = Json.getJson().toJson(vals);

        String callback = getPara("callback");
        if (callback == null) {

            /**
             * <pre style="word-wrap: break-word; white-space: pre-wrap;">
             *     {
             *     "name":"84791408810118438.jpg",
             *     "originalName": "Service1.jpg",
             *     "size": 4680,
             *     "state": "SUCCESS",
             *     "type": ".jpg",
             *     "url": "upload/20140824/84791408810118438.jpg"
             *     }
             * </pre>
             * //getResponse().getWriter().print( result );
             // 使用renderJson 浏览器总是自动加上pre标签
             */
            renderJson(result);
        }
        else {
            //            getResponse().getWriter().print("<script>"+ callback +"(" + result + ")</script>");
            // 使用renderJson 浏览器总是自动加上pre标签
            renderText("<script>" + callback + "(" + result + ")</script>");
        }
        /*因数据已强制写进writer，此处null*/
        //        renderNull();
    }

}
